import { asyncRoutes, constantRoutes } from "@/router";
import menuApi from "@/api/menu";
/* Layout */
import Layout from "@/layout";

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * 后台查询的菜单数据拼接成路由格式的数据
 * @param routes
 * @param data
 * @param is_children
 */
export function generaMenu(data) {
  let routes = [
    {
      path: "*",
      redirect: "/404",
      hidden: true,
    },
  ];
  for (const r of data) {
    var route = {
      path: r.path,
      component:
        r.component === "#"
          ? Layout
          : (resolve) => require([`@/views${r.component}`], resolve),
      redirect: r.redirect,
      name: r.name,
      meta: r.mate,
      children: [],
    };
    var needChilren = [];
    for (const children of r.children) {
      if (children.component === "/inventorys/index") {
        var ch = {
          path: children.path,
          name: children.name,
          component: (resolve) =>
            require([`@/views${children.component}`], resolve),
          meta: children.mate,
          hidden: true,
        };
      } else {
        var ch = {
          path: children.path,
          name: children.name,
          component: (resolve) =>
            require([`@/views${children.component}`], resolve),
          meta: children.mate,
        };
      }

      needChilren.push(ch);
    }
    route.children = needChilren;
    routes.push(route);
  }

  return routes;
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(roles) {}

const state = {
  routes: [],
  addRoutes: [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
};

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve) => {
      // 获取动态路由

      menuApi.getByRoleName(roles).then((response) => {
        const loadMenuData = generaMenu(response.data);
        commit("SET_ROUTES", loadMenuData);
        resolve(loadMenuData);
      });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
